package com.network.util;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public final class InetAddressUtil
{
	private InetAddress inetAddress = null;

	public final boolean isBetween(InetAddress minAddr, InetAddress maxAddr) throws IOException
	{
		if (inetAddress == null)
		{
			throw new IOException("current inetAddress is null");
		}
		if (minAddr != null && minAddr.getClass().equals(inetAddress.getClass()) == false)
		{
			throw new IOException("minAddr.class isn't same with inetAddress.class");
		}
		if (maxAddr != null && maxAddr.getClass().equals(inetAddress.getClass()) == false)
		{
			throw new IOException("maxAddr.class isn't same with inetAddress.class");
		}
		boolean bValue = false;
		if (isInet4Address(inetAddress))
		{
			long minLong = Long.MIN_VALUE;
			if (minAddr != null)
			{
				minLong = ByteUtil.byte2long(minAddr.getAddress(), 0);
			}
			long maxLong = Long.MAX_VALUE;
			if (maxAddr != null)
			{
				maxLong = ByteUtil.byte2long(maxAddr.getAddress(), 0);
			}
			long curLong = 0;
			if (minLong > maxLong)
			{
				curLong = minLong;
				maxLong = minLong;
				minLong = curLong;
			}
			curLong = ByteUtil.byte2long(inetAddress.getAddress(), 0);
			if (curLong > minLong && curLong < maxLong)
			{
				bValue = true;
			}
		}
		else
		{
		}
		return bValue;
	}

	public final InetAddress nextInetAddress() throws IOException
	{
		if (inetAddress == null)
		{
			throw new IOException("current inetAddress is null");
		}
		InetAddress inetAddr = null;
		if (isInet4Address(inetAddress))
		{
			long nextLong = ByteUtil.byte2long(inetAddress.getAddress(), 0) + 1;
			inetAddr = InetAddress.getByAddress(ByteUtil.num2byte(nextLong, 4));
		}
		else
		{
		}
		return inetAddr;
	}

	public final boolean isInet4Address(InetAddress inetAddr)
	{
		boolean bValue = true;
		if (inetAddr instanceof Inet4Address)
		{
			bValue = true;
		}
		else
		{
			bValue = false;
		}
		return bValue;
	}

	public static void main(String args[])
	{
		InetAddressUtil iau = new InetAddressUtil();
		try
		{
			iau.setInetAddress(InetAddress.getByName("192.168.6.96"));
			System.out.println(iau.isBetween(InetAddress.getByName("192.168.6.10"), InetAddress.getByName("192.168.6.90")));
			System.out.println(iau.isInet4Address(iau.inetAddress));
			System.out.println(iau.nextInetAddress().getHostAddress());
		}
		catch (UnknownHostException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public final InetAddress getInetAddress()
	{
		return inetAddress;
	}

	public final void setInetAddress(InetAddress inetAddress)
	{
		this.inetAddress = inetAddress;
	}
}
